import React, { useEffect, useState, useRef } from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import './index.less';
import { observer } from 'mobx-react-lite';
import CommonPopup from '../commonPopup';
import { AtSearchBar } from 'taro-ui';
import { topicListFun } from '@/src/common/method/publishFun';

interface AddTopicPopupProps {
  visible: boolean;
  onClose: () => void;
  selectedTopic: (str: string) => void;
}

const AddTopicPopup: React.FC<AddTopicPopupProps> = ({
  visible,
  onClose,
  selectedTopic,
}) => {
  const [searchValue, setSearchValue] = useState<string>('');
  const [list, setList] = useState<any>([]);

  //  友好提示节流 ---
  const lastToastTsRef = useRef(0);
  const toast = (title: string) => {
    const now = Date.now();
    if (now - lastToastTsRef.current > 1200) {
      lastToastTsRef.current = now;
      Taro.showToast({ title, icon: 'none', duration: 1500 });
    }
  };

  //  表情清理工具 ---
  // 1) 清理所有超出 BMP 的码点（大部分 emoji），同时去除 VS16/ZWJ/旗帜标签/组合键帽
  const stripAstralAndControls = (input: string) =>
    Array.from(input)
      .filter((ch) => {
        const cp = ch.codePointAt(0)!;
        // 过滤：astral 平面、ZWJ、VS16、标签序列、键帽组合符
        if (cp > 0xffff) return false; // 绝大多数 emoji
        if (cp === 0x200d) return false; // ZWJ
        if (cp >= 0xfe00 && cp <= 0xfe0f) return false; // 变体选择符
        if (cp >= 0xe0020 && cp <= 0xe007f) return false; // 标签序列(旗帜)
        if (cp === 0x20e3) return false; // 组合键帽
        return true;
      })
      .join('');

  // 2) 进一步清理 BMP 内的常见表情/符号区段（保守覆盖）
  const BMP_EMOJI_REGEX =
    /[\u2190-\u21FF\u2300-\u23FF\u2460-\u24FF\u25A0-\u25FF\u2600-\u27BF\u2B00-\u2BFF\u2934-\u2935\u3297\u3299\u3030\u303D\u00A9\u00AE]/g;

  const sanitizeNoEmoji = (s: string) => {
    let out = stripAstralAndControls(s);
    out = out.replace(BMP_EMOJI_REGEX, '');
    return out;
  };

  const hasEmoji = (s: string) => sanitizeNoEmoji(s) !== s;

  // 选择话题点击事件
  const selectTopic = (string: string) => {
    selectedTopic(string);
  };

  // 热度转化单位
  const formatHeatNum = (numStr: string) => {
    const num = Number(numStr);
    if (isNaN(num)) return numStr;
    if (num < 10000) return `${num}`;
    if (num < 100000000) return `${(num / 10000).toFixed(2)}万`;
    return `${(num / 100000000).toFixed(2)}亿`;
  };

  // 获取话题
  const getTopicList = (keyword: string) => {
    const data = { keyword };
    topicListFun(data)
      .then((res: any) => {
        if (res && res.length > 0) {
          setList(res);
        } else {
          setList([]);
        }
      })
      .catch((err: any) => {
        console.log(err, 'topic list error');
      });
  };

  // 输入框输入触发事件
  const onChange = (val: string) => {
    // CHANGED
    // 先做清理
    const cleaned = sanitizeNoEmoji(val);
    if (cleaned !== val) {
      toast('暂不支持输入表情符号~');
    }
    setSearchValue(cleaned);
    getTopicList(cleaned);
  };

  useEffect(() => {
    getTopicList('');
  }, []);

  const content = () => {
    return (
      <View className="topic-popup-container">
        <View className="topic-search"></View>
        <AtSearchBar
          placeholder="搜索话题"
          showActionButton={true}
          className="custom-search-bar"
          value={searchValue}
          onChange={(val) => onChange(String(val))} // CHANGED: 强制字符串 & 统一入口清理
        />
        <View className="topic-content-container">
          {list.map((item: any) => {
            return (
              <View
                key={item.id || item.topicName}
                className="content-item"
                onClick={() => selectTopic(item)}
              >
                <View className="topic">#{item.topicName}</View>
                <View className="topic-hot">
                  {formatHeatNum(item.topicHeatNum)}热度
                </View>
              </View>
            );
          })}
        </View>
      </View>
    );
  };

  return (
    <View className="topic-container">
      <CommonPopup
        visible={visible}
        onClose={onClose}
        title="添加话题"
        className="topic-popup"
        content={content()}
      />
    </View>
  );
};

export default observer(AddTopicPopup);
